package web

import (
	"jgt-oper/src/bll"
	"jgt-oper/src/context"
	"jgt-oper/src/schema"
	"jgt-oper/src/util"
	"strings"
)

// AppVersion 应用版本管理
type AppVersion struct {
	AppVersionBll *bll.AppVersion `inject:""`
}

// QueryPage 查询分页数据
func (a *AppVersion) QueryPage(ctx *context.Context) error {
	pageIndex, pageSize := ctx.GetPageIndex(), ctx.GetPageSize()

	params := schema.AppVersionQueryParam{
		DeviceType: ctx.Query("device_type"),
		Name:       ctx.Query("name"),
		Title:      ctx.Query("title"),
		Status:     util.S(ctx.Query("status")).Int(),
		Upgrade:    util.S(ctx.Query("upgrade")).Int(),
	}

	total, items, err := a.AppVersionBll.QueryPage(params, pageIndex, pageSize)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}

	result := map[string]interface{}{
		"list": items,
		"pagination": map[string]interface{}{
			"total":    total,
			"current":  pageIndex,
			"pageSize": pageSize,
		},
	}

	return ctx.ResSuccess(result)
}

// Get 精确查询数据
func (a *AppVersion) Get(ctx *context.Context) error {
	item, err := a.AppVersionBll.Get(ctx.Param("id"))
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(item)
}

// Create 创建数据
func (a *AppVersion) Create(ctx *context.Context) error {
	var item schema.AppVersion
	if err := ctx.ParseJSON(&item); err != nil {
		return ctx.ResErrBadRequest(err)
	}

	item.Creator = ctx.GetUserID()
	err := a.AppVersionBll.Create(&item)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// Update 更新数据
func (a *AppVersion) Update(ctx *context.Context) error {
	var item schema.AppVersion
	if err := ctx.ParseJSON(&item); err != nil {
		return ctx.ResErrBadRequest(err)
	}

	err := a.AppVersionBll.Update(item.RecordID, &item)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// Enable 启用数据
func (a *AppVersion) Enable(ctx *context.Context) error {
	err := a.AppVersionBll.UpdateStatus(ctx.Param("id"), 1)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// Disable 禁用数据
func (a *AppVersion) Disable(ctx *context.Context) error {
	err := a.AppVersionBll.UpdateStatus(ctx.Param("id"), 2)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// DeleteMany 删除多条数据
func (a *AppVersion) DeleteMany(ctx *context.Context) error {
	ids := strings.Split(ctx.Query("batch"), ",")

	for _, id := range ids {
		err := a.AppVersionBll.Delete(id)
		if err != nil {
			return ctx.ResErrInternalServer(err)
		}
	}

	return ctx.ResOK()
}

// Delete 删除数据
func (a *AppVersion) Delete(ctx *context.Context) error {
	err := a.AppVersionBll.Delete(ctx.Param("id"))
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}
